﻿using Enring.Model.Range;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.UI.WebControls;


namespace Enring.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        bool hasChanged = false;
        bool hasContriesChanged = false;
        EnringContext ec = EnringContext.Current;
        Ring pRing = null;
        int pageSize = 5;
        int pageIndex = 1;
        protected void Page_Load(object sender, EventArgs e)
        {

            btnAppendRing.Click += new EventHandler(btnAppendRing_Click);
            btnRefresh.Click += new EventHandler(btnRefresh_Click);
            btnAppend.Click += new EventHandler(btnAppend_Click);
            btnDeleteContry.Click += new EventHandler(btnDeleteContry_Click);
            gridRings.RowDeleting += new GridViewDeleteEventHandler(GridView1_RowDeleting);
            gridRings.SelectedIndexChanged += new EventHandler(gridRings_SelectedIndexChanged);
            menuPath.MenuItemClick += new MenuEventHandler(menuPath_MenuItemClick);
            lstContries.SelectedIndexChanged += new EventHandler(lstContries_SelectedIndexChanged);
            pager.MenuItemClick += new MenuEventHandler(pager_MenuItemClick);
            ec.Rings.Load();
            ec.Countries.Load();
            this.PreRender += new EventHandler(_Default_PreRender);
            if (menuPath.Items.Count > 1)
            {
                int rid = int.Parse(menuPath.Items[menuPath.Items.Count-1].Value);
                Ring r = ec.Rings.Where(row => row.ID == rid).First();
                pRing = r;
            }

            
        }

        void pager_MenuItemClick(object sender, MenuEventArgs e)
        {
            pageIndex = int.Parse(e.Item.Value);
            hasChanged = true;

        }

        void lstContries_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillPath(null);
        }

        void menuPath_MenuItemClick(object sender, MenuEventArgs e)
        {
            int rid = int.Parse(e.Item.Value);
            if (rid > 0)
            {
                Ring r = ec.Rings.Where(row => row.ID == rid).First();
                pRing = r;
            }
            else
                pRing = null;
            hasChanged = true;
            FillPath(pRing);
        }

        void gridRings_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (gridRings.SelectedIndex >= 0)
            {
                int rid = int.Parse(gridRings.SelectedRow.Cells[0].Text);
                Ring pr = ec.Rings.Where(row => row.ID == rid).First();
                FillPath(pr);
                pRing = pr;
                hasChanged = true;
            }

        }
        void FillPath(Ring r) {
            menuPath.Items.Clear();
            if(r!=null)
                menuPath.Items.Add(new MenuItem(r.Country.Name, "0"));
            else
                menuPath.Items.Add(new MenuItem(lstContries.SelectedItem.Text, "0"));
            ParentRing(r);
        }
        void ParentRing(Ring current) {
            if (current != null)
                menuPath.Items.AddAt(1,new MenuItem() {  Text=current.Name, Value=current.ID.ToString() });
            if (current!=null && current.Parent != null)
                ParentRing(current.Parent);
            
        }

        void btnAppendRing_Click(object sender, EventArgs e)
        {
            hasChanged = true;
            int cid = lstContries.SelectedIndex >= 0 ? cid = int.Parse(lstContries.SelectedValue) : -1;
            if (cid >= 0)
            {
                Country c = ec.Countries.Where(row => row.ID == cid).First();
                Ring r = new Ring() { Name = "TEST" + (ec.Rings.Count() + 1) };
                if (gridRings.SelectedIndex >= 0)
                {
                    int rid = int.Parse(gridRings.SelectedRow.Cells[0].Text);
                    Ring pr = ec.Rings.Where(row => row.ID == rid).First();
                    r.Level = pr.Level + 1;
                    pr.Children.Add(r);
                }
                else if (pRing != null)
                {
                    pRing.Children.Add(r);
                    r.Level = pRing.Level + 1;
                }
                else
                    r.Level = 1;
                c.Rings.Add(r);
                ec.SaveChanges();
            }

        }
        
        void btnRefresh_Click(object sender, EventArgs e)
        {
            hasChanged = true;
            
        }

        void btnDeleteContry_Click(object sender, EventArgs e)
        {
            hasContriesChanged = true;
            int id = int.Parse(lstContries.SelectedValue);
            var list = ec.Countries.Where(row => row.ID == id);
            foreach (var itm in list)
            {
                //itm.Rings.Clear();
                ec.Countries.Remove(itm);
            }
            ec.SaveChanges();
        }

        void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            hasChanged = true;
            int id = int.Parse(e.Values["ID"].ToString());
            var list = ec.Rings.Where(row => row.ID == id);
            foreach (var itm in list)
                ec.ObjectContext.DeleteObject(itm);
            ec.SaveChanges();
             
        }

        void _Default_PreRender(object sender, EventArgs e)
        {
            if ((hasContriesChanged |hasChanged) || !IsPostBack)
            {
                int cid = lstContries.SelectedIndex >= 0 ? cid = int.Parse(lstContries.SelectedValue) : -1;
                if (hasContriesChanged || !IsPostBack)
                {

                    lstContries.DataSource = ec.Countries.Local.ToBindingList();
                    lstContries.DataBind();
                    if(ec.Countries.Count() > 0 & cid ==-1)
                        cid = ec.Countries.First().ID;
                }
                if (lstContries.Items.FindByValue(cid.ToString()) != null)
                    lstContries.Items.FindByValue(cid.ToString()).Selected = true;
                else
                    cid = -1;
                if (cid >= 0)
                {
                    Country ctry = ec.Countries.Where(row => row.ID == cid).First();
                    gridRings.SelectedIndex = -1;
                    IEnumerable<Ring> record = null;
                    //两种写法
                    if (pRing == null)
                        record = from t in ctry.Rings orderby t.ID where t.Level==1 select t;
                    else
                        record = ctry.Rings.Where(row => row.Level == pRing.Level + 1 & row.Parent == pRing).OrderBy(o => o.ID);
                    int count = record.Count();
                    int totalPageNum = (count + pageSize-1 ) / pageSize +1;
                     
                    pager.Items.Clear();
                    for (int i = 1; i < totalPageNum; i++)
                        pager.Items.Add(new MenuItem(i.ToString(), i.ToString()));
                    gridRings.DataSource = record.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                    gridRings.DataBind();
                }
            }
        }

        void btnAppend_Click(object sender, EventArgs e)
        {
            hasContriesChanged = true;
            List<TimeZoneInfo> htzs = new List<TimeZoneInfo>();
            foreach (Country co in ec.Countries) {
                TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(co.TimeZone);
                htzs.Add(tzi);
            }
            TimeZoneInfo newc = TimeZoneInfo.GetSystemTimeZones().Except(htzs).First();
            Country c = new Country();
            c.Name = newc.DisplayName;
            c.TimeZone = newc.Id;
            ec.Countries.Add(c);
            ec.SaveChanges();


        }
    }
}
